package com.example.boot1;

import java.util.concurrent.TimeUnit;

//线程操作资源类
class HoldLockThread implements Runnable {

    private String lockA;
    private String lockB;

    public HoldLockThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized(lockA){
            System.out.println(Thread.currentThread().getName()+"\t 自己持有:" +lockA +",尝试获得锁"+lockB);
            try{ TimeUnit.SECONDS.sleep(2);} catch(Exception e){e.printStackTrace();}
            synchronized(lockB){
                System.out.println(Thread.currentThread().getName()+"\t 自己持有："+lockB+",尝试获得锁"+lockA);

            }
        }
    }
}

/**
 * 死锁是指，两个或两个以上得线程在执行过程中，因抢夺资源造成得一种互相等待得现象。若无外力干涉它们将无法推进下去
 */
public class DeadLockDemo {
    public static void main(String[] args) {
        String lockA="lockA";
        String lockB="lockB";

        new Thread(new HoldLockThread(lockA,lockB), "ThreadAAA").start();
        new Thread(new HoldLockThread(lockB,lockA), "ThreadBBB").start();

    }
}
